let ws;
const ws_url = "ws://localhost:8080/poj-java/chat";
let Ausername = $(".username").val(); 
let Breciveusername = $(".reciveusername").val(); 
let myAvatar = $(".myAvatar").attr('src'); 
let chatWithAvatar = $(".chatWithAvatar").attr('src'); 

$(function() {
    // 先加载历史消息
    selecOurmsg(Ausername, Breciveusername);
    
    //  再建立WebSocket连接
    ws_connect();
    
    // 绑定发送按钮事件
    $("#send-message").click(function(){
        ws_sendMsg();
    });
    
    //  添加回车发送支持
    $("#message").on("keypress", function(e) {
        if (e.which === 13) { // Enter键
            e.preventDefault();
            ws_sendMsg();
        }
    });
});

function ws_connect() {
    const fullUrl = `${ws_url}?sendUsername=${Ausername}&reciveusername=${Breciveusername}`;
    
    if ('WebSocket' in window) {
        ws = new WebSocket(fullUrl);
    } else if ('MozWebSocket' in window) {
        ws = new MozWebSocket(fullUrl);
    } else {
        console.log('Error: WebSocket is not supported by this browser.');
        return;
    }

    ws.onopen = function() {
        console.log('WebSocket连接已建立:', fullUrl);
    };

    ws.onclose = function() {
        console.log('WebSocket连接已关闭');
    };
    
    ws.onmessage = function(message) {
        try {
            const msgData = JSON.parse(message.data);
            console.log("收到消息:", msgData);
            
            // 如果是自己发送的消息，只更新发送时间（不再重复显示）
            if (msgData.sendUsername === Ausername) {
                // 找到对应临时消息并更新
                $('.message.sent.temp').each(function() {
                    const $this = $(this);
                    if ($this.find('.message-bubble').text() === msgData.message) {
                        $this.find('.message-time').text(formatTime(msgData.send_at));
                        $this.removeClass('temp');
                    }
                });
                return;
            }
            
            // 显示接收到的消息
            displayMessage(msgData);
            scrollToBottom();
            
        } catch (e) {
            console.error("解析消息错误:", e);
        }
    };
}

// 消息显示函数
function displayMessage(msgData, isTemp = false) {
    const isSent = msgData.sendUsername === Ausername;
    const messageClass = isSent ? 'message sent' : 'message received';
    const tempClass = isTemp ? ' temp' : '';
    
    const messageHtml = `
        <div class="${messageClass}${tempClass}">
            <div class="message-content">
                ${!isSent ? `<div class="message-name">${msgData.sendUsername}</div>` : ''}
                <div class="message-bubble">${msgData.message}</div>
                <div class="message-time">${isTemp ? '发送中...' : formatTime(msgData.send_at)}</div>
            </div>
        </div>
    `;
    
    $('.chat-messages').append(messageHtml);
}

function ws_sendMsg() {
    const msg = $("#message").val().trim();
    if (!msg) return;

    const data = {
        sendUsername: Ausername,
        reciveusername: Breciveusername,
        message: msg
    };
    
    console.log("发送消息:", JSON.stringify(data));
    
    if (ws && ws.readyState === WebSocket.OPEN) {
        // 立即在本地显示自己发送的消息（临时状态）
        const tempMsg = {
            sendUsername: Ausername,
            reciveusername: Breciveusername,
            message: msg,
            send_at: new Date()
        };
        displayMessage(tempMsg, true);
        scrollToBottom();
        
        ws.send(JSON.stringify(data));
        $("#message").val("");
    } else {
        console.error('WebSocket未连接');
        alert('连接已断开，请刷新页面');
    }
}

// 时间格式化函数
function formatTime(dateStr) {
    if (!dateStr) return '';
    
    const date = new Date(dateStr);
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
}

// 滚动到底部
function scrollToBottom() {
    const chatMessages = $('.chat-messages')[0];
    if (chatMessages) {
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }
}

// 统一消息渲染格式
function selecOurmsg(sender, receiver) {
    $.ajax({
        url: "getChaertingRecords.do",
        type: "GET",
        data: {
            sendUsername: sender,
            reciveusername: receiver,
        },
        success: function(data) {
            console.log("聊天记录数据:", data);
            let html = '';
            
            if (data.data && data.data.length > 0) {
                data.data.forEach(msg => {
                    const isSent = msg.sendUsername === sender;
                    const messageClass = isSent ? 'message sent' : 'message received';
                    
                    html += `
                        <div class="${messageClass}">    
                            <div class="message-content">
                                ${!isSent ? `<div class="message-name">${msg.sendUsername}</div>` : ''}
                                <div class="message-bubble">${msg.message}</div>
                                <div class="message-time">${formatTime(msg.send_at)}</div>
                            </div>
                        </div>
                    `;
                });
            } else {
                html = '<div class="no-messages">没有聊天记录</div>';
            }
            
            $('.chat-messages').html(html);
            scrollToBottom();
        }
    });
}